﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChuanYe.Models;
using System.Data.Entity.Core.Objects;
using ChuanYe.IDAL;
using ChuanYe.Models.Model;
using System.IO;
using EntityFramework.Extensions;
using ChuanYe.Utils;

namespace ChuanYe.DAL
{
    public class MailDAL: IMailDAL
    {
        /// <summary>
        /// 获取全部邮箱用户
        /// </summary>
        /// <returns></returns>
        public List<ChuanYe.Models.Model.View_MailUsers> GetAllMailUsers()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                IQueryable<ChuanYe.Models.Model.View_MailUsers> list =
                    db.UsersInfos.Select(M => new ChuanYe.Models.Model.View_MailUsers
                    {
                        DepID = M.Section,
                        Division = M.Division,
                        Sort = M.Sort,
                        UserID = M.ID,
                        UserName = M.UserName,
                        Phone=M.Phone,
                        IsManager= M.IsManager,
                    });
                    
                return list.ToList();
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CreateInfosComm(InfosComm model, List<InfosCommAttachs> InfosCommAttachsModel)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.InfosComm.Add(model);
                bool result= db.SaveChanges() > 0 ? true : false;
                foreach (InfosCommAttachs Attach in InfosCommAttachsModel)
                {
                    Attach.InforId = model.ID;
                }
                db.InfosCommAttachs.AddRange(InfosCommAttachsModel);
                db.SaveChanges();
                return result;
            }
        }

        /// <summary>
        /// 保存附件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CreateInfosCommAttachs(InfosCommAttachs model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.InfosCommAttachs.Add(model);
                return db.SaveChanges() > 0 ? true : false;
            }
        }

        /// <summary>
        /// 接收的邮件
        /// </summary>
        /// <param name="Search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public ReceiveMailListResult ReceiveMailGetList(ReceiveMailSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                ReceiveMailListResult result = new ReceiveMailListResult();
                if (Search.IsView != null)
                {
                    var rst = db.InfosComm.Join(
                        db.UsersInfos,
                        A => A.From,
                        B => B.ID,
                        (A, B) => new ReceiveMailModel
                        {
                            ID = A.ID,
                            FromName = B.UserName,
                            Title = A.Title,
                            PublishTime = A.PublishTime,
                            IsView = A.IsView,
                            To = A.To
                        }
                        ).Where(M => M.To == Search.UserID &&
                        M.IsView == Search.IsView && ((string.IsNullOrEmpty(Search.Keyword)) || M.FromName.Contains(Search.Keyword))
                        );
                    result.NewsTempList = rst
                        .OrderByDescending(f => f.PublishTime)
                        .Skip(Pager.rows * (Pager.page - 1))
                        .Take(Pager.rows)
                        .ToList();
                    result.totalRows = rst.Count();
                }
                else {
                    var rst = db.InfosComm.Join(
                        db.UsersInfos,
                        A => A.From,
                        B => B.ID,
                        (A, B) => new ReceiveMailModel
                        {
                            ID = A.ID,
                            FromName = B.UserName,
                            Title = A.Title,
                            PublishTime = A.PublishTime,
                            IsView = A.IsView,
                            To = A.To
                        }
                        ).Where(M => M.To == Search.UserID &&  ((string.IsNullOrEmpty(Search.Keyword))|| M.FromName.Contains(Search.Keyword))
                        );
                    result.NewsTempList = rst.
                        OrderBy(m => m.IsView)
                        .ThenByDescending(P => P.PublishTime)
                        .Skip(Pager.rows * (Pager.page - 1))
                        .Take(Pager.rows)
                        .ToList();
                    result.totalRows = rst.Count();
                }
                return result;
            }
        }

        /// <summary>
        /// 邮件详情
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public InfosCommInfoModel InfosCommGet(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.InfosComm
                    .Join(
                    db.UsersInfos,
                    A=>A.From,
                    B=>B.ID,
                    (A,B)=>new InfosCommInfoModel
                    {
                        Brief = A.Brief,
                        FromName = B.UserName,
                        FSState = A.FSState,
                        GGState = A.GGState,
                        ID = A.ID,
                        InfosCode = A.InfosCode,
                        IsView = A.IsView,
                        JSState = A.JSState,
                        PublishTime = A.PublishTime,
                        Title = A.Title
                    }
                    )
                    .FirstOrDefault(M => M.ID == ID);
            }
        }
        /// <summary>
        /// 邮件附件列表
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public List<InfosCommAttachs> InfosCommAttachsGet(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.InfosCommAttachs.Where(M => M.InforId == ID).ToList();
            }
        }
        /// <summary>
        /// 删除邮件
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int InfosCommDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.InfosComm.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    List<DocumentAttachs> List = db.DocumentAttachs.Where(m => m.DocumentID == Info.ID).ToList();
                    foreach (DocumentAttachs DA in List)
                    {
                        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DA.FilePath);
                        File.Delete(filePath);
                    }
                    db.DocumentAttachs.RemoveRange(List);
                    db.SaveChanges();
                    db.InfosComm.Remove(Info);
                }
                int i = db.SaveChanges();
                return i;
            }
        }
        /// <summary>
        /// 改变已读状态
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int InfosCommUpdate(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                InfosComm Info = db.InfosComm.FirstOrDefault(m => m.ID == ID);
                Info.IsView = true;
                int i = db.SaveChanges();
                return i;
            }
        }

        /// <summary>
        /// 批量更改已读状态
        /// </summary>
        /// <param name="IDs"></param>
        /// <returns></returns>
        public int InfosCommUpdateByIDs(int[] IDs)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                if (IDs != null && IDs.Length > 0)
                {
                    return db.InfosComm.Where(p => IDs.Contains(p.ID)).Update(u => new InfosComm { IsView = true });
                }
                return 0;
            }
        }


        /// <summary>
        /// 公共邮箱列表
        /// </summary>
        /// <param name="Search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public PublicMailResult PublicMailGetList(PublicMailSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                if (Search.IsView != null)
                {
                    var linq = db.InfosComm.
                        Join(
                        db.UsersInfos,
                        I => I.From,
                        U => U.ID,
                        (I, U) => new MailPublicModel
                        {
                            ID = I.ID,
                            To = I.To,
                            FromName = U.UserName,
                            FSState = I.FSState,
                            GGState = I.GGState,
                            IsView = I.IsView,
                            JSState = I.JSState,
                            PublishTime = I.PublishTime,
                            Title = I.Title
                        })
                        .DefaultIfEmpty()
                        .Where(m => m.To == db.UsersInfos.FirstOrDefault(
                        B => B.Section == db.UsersInfos.FirstOrDefault(D => D.ID == Search.UserID).Section &&
                        B.Division == 1).ID &&
                        m.IsView == Search.IsView && ((string.IsNullOrEmpty(Search.Keyword)) || m.FromName.Contains(Search.Keyword))
                        )
                        .OrderByDescending(P => P.PublishTime);
                    PublicMailResult result = new PublicMailResult();
                    result.PublicMailList = linq.Skip(Pager.rows * (Pager.page - 1)).Take(Pager.rows).ToList();
                    result.totalRows = linq.Count();
                    return result;
                }
                else {
                    var linq = db.InfosComm.
                        Join(
                        db.UsersInfos,
                        I => I.From,
                        U => U.ID,
                        (I, U) => new MailPublicModel
                        {
                            ID = I.ID,
                            To = I.To,
                            FromName = U.UserName,
                            FSState = I.FSState,
                            GGState = I.GGState,
                            IsView = I.IsView,
                            JSState = I.JSState,
                            PublishTime = I.PublishTime,
                            Title = I.Title
                        })
                       
                        //.DefaultIfEmpty()
                        .Where(m => m.To == db.UsersInfos.FirstOrDefault(
                        B => B.Section == db.UsersInfos.FirstOrDefault(D => D.ID == Search.UserID).Section &&
                        B.Division == 1).ID && ((string.IsNullOrEmpty(Search.Keyword)) || m.FromName.Contains(Search.Keyword))
                        )
                        .OrderBy(m => m.IsView)
                        .ThenByDescending(P => P.PublishTime);
                    PublicMailResult result = new PublicMailResult();
                    result.PublicMailList= linq.Skip(Pager.rows * (Pager.page - 1)).Take(Pager.rows).ToList();
                    result.totalRows = linq.Count();
                    return result;
                }
            }
        }
        /// <summary>
        /// 已发邮件列表
        /// </summary>
        /// <param name="Search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public MailSendResult MailSendGetList(MailSendSearch Search, GridPager Pager)
        {

            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                MailSendResult modle = new MailSendResult();
                if (Search.IsView != null)
                {

                    var result = db.InfosComm
                        .Join(
                        db.UsersInfos,
                        A => A.To,
                        B => B.ID,
                        (A, B) => new MailSendModel
                        {
                            ID = A.ID,
                            From = A.From,
                            ToName = B.UserName,
                            Title = A.Title,
                            PublishTime = A.PublishTime,
                            IsView = A.IsView
                        }
                        )
                        .DefaultIfEmpty()
                        .Where(m => m.From == Search.UserID &&
                        m.IsView == Search.IsView && ((string.IsNullOrEmpty(Search.Keyword)) || m.ToName.Contains(Search.Keyword))
                        )
                        .OrderByDescending(P => P.PublishTime);
                    modle.MailSendModelList = result.Skip(Pager.rows * (Pager.page - 1)).Take(Pager.rows).ToList();
                    modle.totalRows = result.Count();
                }
                else {

                    var result = db.InfosComm
                        .Join(
                        db.UsersInfos,
                        A => A.To,
                        B => B.ID,
                        (A, B) => new MailSendModel
                        {
                            ID = A.ID,
                            From = A.From,
                            ToName = B.UserName,
                            Title = A.Title,
                            PublishTime = A.PublishTime,
                            IsView = A.IsView
                        }
                        )
                        .DefaultIfEmpty()
                        .Where(m => m.From == Search.UserID && ((string.IsNullOrEmpty(Search.Keyword)) || m.ToName.Contains(Search.Keyword))
                        )
                        .OrderBy(m => m.IsView)
                        .ThenByDescending(P => P.PublishTime);
                    modle.MailSendModelList = result.Skip(Pager.rows * (Pager.page - 1)).Take(Pager.rows).ToList();
                    modle.totalRows = result.Count();
                }
                return modle;
            }
        }

        /// <summary>
        /// 获取用户接收到的邮件的附件总大小
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public decimal GetAllInfosCommAttachsSize(int UserID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.InfosCommAttachs
                    .Join(db.InfosComm,
                    A => A.InforId,
                    B => B.ID,
                    (A, B) => new { To = B.To, FileSize = A.FileSize }
                    )
                    .Where(M => M.To == UserID)
                    .GroupBy(m => m.To)
                    .Select(M => M.Sum(S => S.FileSize)).FirstOrDefault();
                return Convert.ToDecimal(Info);
            }
        }

        /// <summary>
        /// 添加日程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int ScheduleCreate(Schedule model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.Schedule.Add(model);
                db.SaveChanges();
                return model.S_ID;
            }
        }
        /// <summary>
        /// 获取日程
        /// </summary>
        /// <param name="S_ID"></param>
        /// <returns></returns>
        public Schedule ScheduleGet(int S_ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Schedule.FirstOrDefault(M => M.S_ID == S_ID);
            }
        }
        /// <summary>
        /// 获取某个月的日程信息
        /// </summary>
        /// <param name="Search"></param>
        /// <returns></returns>
        public List<ScheduleGetMonthListResult> ScheduleGetMonthList(ScheduleSearch Search)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Schedule.Where(
                    m => m.S_TransUser == Search.UserID &&
                    m.S_Date >= Search.stateTime &&
                    m.S_Date <= Search.endTime
                    ).Select(t=>new ScheduleGetMonthListResult { S_ID=t.S_ID, S_Title=t.S_Title, S_Date = t.S_Date })
                    .ToList();
            }
        }
        /// <summary>
        /// 获取某天的日程信息
        /// </summary>
        /// <param name="Search"></param>
        /// <returns></returns>
        public List<ScheduleGetMonthListResult> ScheduleGetDayList(ScheduleSearch Search)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Schedule.Where(
                    m => m.S_TransUser == Search.UserID &&
                    m.S_Date >= Search.stateTime &&
                    m.S_Date <= Search.endTime
                    ).Select(t => new ScheduleGetMonthListResult { S_ID = t.S_ID, S_Title=t.S_Title , S_AutomaticState=t.S_AutomaticState })
                    .ToList();
            }
        }
        /// <summary>
        /// 修改日程信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int ScheduleUpdate(Schedule model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                Schedule Info = db.Schedule.FirstOrDefault(m => m.S_ID == model.S_ID);
                Info.S_Title = model.S_Title;
                Info.S_Cont = model.S_Cont;
                Info.S_Date = model.S_Date;
                Info.S_TsDate = model.S_TsDate;
                Info.S_TsTime = model.S_TsTime;
                Info.S_Int = model.S_Int;
                int i = db.SaveChanges();
                return i;
            }
        }

        /// <summary>
        /// 修改日程信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int ScheduleAutomaticStateUpdate(Schedule model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Schedule.Where(p=>p.S_ID==model.S_ID).Update(u=>new Schedule() { S_AutomaticState=model.S_AutomaticState});
            }
        }

        /// <summary>
        /// 删除日程信息
        /// </summary>
        /// <param name="S_ID"></param>
        /// <returns></returns>
        public int ScheduleDelete(int S_ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Schedule.FirstOrDefault(m => m.S_ID == S_ID);
                if (Info != null)
                {
                    db.Schedule.Remove(Info);
                }
                int i = db.SaveChanges();
                return i;
            }
        }
        
    }
}
